package org.west.sky.scripture.elegantdemo.exception;

import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.west.sky.scripture.elegantdemo.response.ResultCode;
import org.west.sky.scripture.elegantdemo.response.ResultVO;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Optional;


/**
 * @author chenghz
 * @date 2022/6/21 10:27
 * @description: 全局异常捕获
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({BindException.class})
    public ResultVO bindExceptionHandler(BindException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new ResultVO(ResultCode.VALIDATE_ERROR, objectError.getDefaultMessage());
    }

    @ExceptionHandler({ConstraintViolationException.class})
    public ResultVO constraintViolationExceptionHandler(ConstraintViolationException e) {
        Optional<ConstraintViolation<?>> first = e.getConstraintViolations().stream().findFirst();
        return first.map(constraintViolation -> new ResultVO(ResultCode.VALIDATE_ERROR, constraintViolation.getMessage())).orElseGet(() -> new ResultVO(ResultCode.VALIDATE_ERROR));
    }

    @ExceptionHandler(BizException.class)
    public ResultVO bizExceptionHandler(BizException e) {
        // log.error(e.getMessage(), e); 由于还没集成日志框架，暂且放着，写上TODO
        return new ResultVO(e.getCode(), e.getMsg(), e.getMessage());
    }
}
